package com.minshenglife.zanzan.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.minshenglife.zanzan.dao.ArticleDao;
import com.minshenglife.zanzan.dao.AutomaticReplyDao;
import com.minshenglife.zanzan.dao.KeywordDao;
import com.minshenglife.zanzan.dao.MaterialDao;
import com.minshenglife.zanzan.entity.weixin.ArticleTodb;
import com.minshenglife.zanzan.entity.weixin.AutomaticReply;
import com.minshenglife.zanzan.entity.weixin.Keyword;
import com.minshenglife.zanzan.entity.weixin.Material;
import com.minshenglife.zanzan.service.AutomaticReplyService;

/**
 * 微信自动回复service
 * @author jianghaibo
 *
 */
@Component
@Transactional
public class AutomaticReplyServiceImpl implements AutomaticReplyService{
	@Resource
	AutomaticReplyDao automaticReplyDao;
	@Resource
	MaterialDao materialDao;
	@Resource
	ArticleDao articleDao;
	@Resource
	KeywordDao keywordDao;
	
	@Override
	public AutomaticReply get(Long automaticId) {
		return automaticReplyDao.get(automaticId);
	}

	@Override
	public List<AutomaticReply> findAllByAppid(String appid) {
		AutomaticReply arg = new AutomaticReply();
		arg.setAppid(appid);
		List<AutomaticReply> automaticReplies = automaticReplyDao.findByExample(arg);
		for (AutomaticReply automaticReply : automaticReplies) {
			Material material = materialDao.get(automaticReply.getMaterialId());
			if(material != null && material.getMaterialType() != null && material.getMaterialType().equals("news")){
				ArticleTodb article = new ArticleTodb();
				article.setMaterialId(material.getId());
				List<ArticleTodb> articleList = articleDao.findByExample(article);
				material.setArticleList(articleList);
			}
			automaticReply.setMaterial(material);
			
			Keyword keyword = new Keyword();
			keyword.setAutomaticId(automaticReply.getId());
			List<Keyword> keywordList = keywordDao.findByExample(keyword);
			automaticReply.setKeywordList(keywordList);
		}
		return automaticReplies;
	}

	@Override
	public AutomaticReply add(AutomaticReply automaticReply) {
		Long id = automaticReplyDao.findMaxId();
		if(id != null){
			id += 1l;
		}else{
			id = 1l;
		}
		automaticReply.setId(id);
		automaticReplyDao.add(automaticReply);
		return automaticReply;
	}

	@Override
	public boolean delete(AutomaticReply automaticReply) {
		boolean flag = true;
		try {
			automaticReplyDao.deleteByExample(automaticReply);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	@Override
	public void update(AutomaticReply automaticReply) {
		automaticReplyDao.update(automaticReply);
	}
}
